﻿using System;
using System.IO;
using System.Net.Http;
using System.Runtime.InteropServices;

namespace Launcher;

public static class Utils
{
    public static readonly HttpClient HttpClient = new();
    public static OSPlatform GetCurrentPlatform()
    {
        if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
        {
            return OSPlatform.Windows;
        }

        if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
        {
            return OSPlatform.Linux;
        }

        if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
        {
            return OSPlatform.OSX;
        }

        return OSPlatform.Create("Unknown");
    }

    public static string ByteSizeFormat(long size)
    {
        if (size < 1024)
        {
            return $"{size} B";
        }

        if (size < 1024 * 1024)
        {
            return $"{size / 1024.0:F1} KB";
        }

        if (size < 1024 * 1024 * 1024)
        {
            return $"{size / 1024.0 / 1024.0:F1} MB";
        }
        
        if (size < 1024L * 1024 * 1024 * 1024)
        {
            return $"{size / 1024.0 / 1024.0 / 1024.0:F1} GB";
        }

        return $"{size / 1024.0 / 1024.0 / 1024.0 / 1024.0:F1} TB";
    }
    
    public static void MoveDirectory(string sourceDir, string destinationDir, bool overwrite = true)
    {
        if (string.IsNullOrEmpty(sourceDir) || string.IsNullOrEmpty(destinationDir))
        {
            throw new ArgumentException("源目录或目标目录路径不能为空");
        }

        // 确保源目录存在
        if (!Directory.Exists(sourceDir))
        {
            throw new DirectoryNotFoundException($"源目录 '{sourceDir}' 不存在");
        }

        // 如果目标目录不存在，则创建它
        if (!Directory.Exists(destinationDir))
        {
            Directory.CreateDirectory(destinationDir);
        }

        // 获取源目录中的所有文件并复制到目标目录
        foreach (var file in Directory.GetFiles(sourceDir, "*.*", SearchOption.AllDirectories))
        {
            var relativePath = file.Substring(sourceDir.Length + 1); // 计算相对路径
            var destFilePath = Path.Combine(destinationDir, relativePath);

            // 确保目标文件夹存在
            var destDir = Path.GetDirectoryName(destFilePath);
            if (!Directory.Exists(destDir))
            {
                Directory.CreateDirectory(destDir);
            }

            // 移动文件（如果需要覆盖）
            File.Move(file, destFilePath, overwrite);
        }

        // 遍历源目录中的所有子目录并递归调用自身
        foreach (var dir in Directory.GetDirectories(sourceDir, "*", SearchOption.TopDirectoryOnly))
        {
            var dirName = Path.GetFileName(dir);
            var destSubDirPath = Path.Combine(destinationDir, dirName);
            MoveDirectory(dir, destSubDirPath, overwrite);
        }
    }
}